package cn.cs.service.impl;

import cn.cs.client.CsPartsClient;
import cn.cs.client.ProductTypeClient;
import cn.cs.common.*;
import cn.cs.pojo.CsParts;
import cn.cs.pojo.CsPartsAttribute;
import cn.cs.pojo.CsPartsQrCode;
import cn.cs.pojo.ProductType;
import cn.cs.service.CsPartsService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class CsPartsServiceImpl implements CsPartsService {

    @Resource
    private CsPartsClient partsClient;

    @Resource
    private ProductTypeClient productTypeClient;

    public CsParts getCsPartsById(String id) throws Exception {
        return partsClient.getCsPartsById(id);
    }

    public List<CsParts> getCsPartsListByMap(Map<String, Object> param) throws Exception {
        return partsClient.getCsPartsListByMap(param);
    }

    public Integer getCsPartsCountByMap(Map<String, Object> param) throws Exception {
        return partsClient.getCsPartsCountByMap(param);
    }

    public Integer addCsParts(CsParts csParts) throws Exception {
        return partsClient.insertCsParts(csParts);
    }

    public Integer addPartsAttribute(CsPartsAttribute partsAttribute) throws Exception {
        return partsClient.addPartsAttribute(partsAttribute);
    }

    public Integer modifyCsParts(CsParts csParts) throws Exception {
        return partsClient.updateCsParts(csParts);
    }

    public Integer updatePartsAttribute(CsPartsAttribute partsAttribute) throws Exception{
        return partsClient.updatePartsAttribute(partsAttribute);
    }

    public Integer deletePartsAttribute(String id) throws Exception{
        return partsClient.deletePartsAttribute(id);
    }

    public Integer deleteCsPartsImgByPartsId(String partsId) throws Exception {
        return partsClient.deleteCsPartsImgByPartsId(partsId);
    }

    public Integer insertCsPartsImgList(List<Map<String, Object>>list) throws Exception {
        return partsClient.insertCsPartsImgList(list);
    }


    public Integer deleteCsPartsById(String id) throws Exception {
        return partsClient.deleteCsPartsById(id);
    }

    public Page<CsParts> queryCsPartsPageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) throws Exception {
        Integer total = partsClient.getCsPartsCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<CsParts> csPartsList = partsClient.getCsPartsListByMap(param);
        for(CsParts a:csPartsList){
            String partsTypeId = a.getPartsType();
            ProductType type = productTypeClient.getProductTypeById(partsTypeId);
            a.setPartsType(type.getTypeName());
        }
        page.setRows(csPartsList);
        return page;
    }



    
    /**
     * 保存二维码数据
     * @param request
     * @param response
     * @return
     */
    public Dto saveQrCodeData(HttpServletRequest request, HttpServletResponse response){
        String partsId = request.getParameter("partsId");
        int num = Integer.valueOf(request.getParameter("num"));
        List<Map<String, Object>> list = Collections.synchronizedList(new ArrayList());
        Date date = new Date();
        String realPath = "";
        try{
            Long code = partsClient.getQrcodeMax(partsId);
            code ++;
            realPath = String.valueOf(code);
            System.out.println("code---------------------------------" + code);
            for(int i=0;i<num;i++){
                Map<String, Object> map = new HashMap<>();
                String QRcode = IdWorker.getId() + DateUtil.format(new Date(), "yyyyMMdd") + nextInt(100000, 999999);
                map.put("QRcode", QRcode);
                map.put("partsId", partsId);
                map.put("createTime", date);
                map.put("code", code);
                list.add(map);
                code ++;
            }
            realPath += "," + String.valueOf(code);
            partsClient.insertCsPartsQRcodeList(list);
            Map<String, String> map = new HashMap<String, String>();
            map.put("realPath", realPath);
            map.put("partsId", partsId);
            return DtoUtil.returnSuccess("操作成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("操作失败", "001");
    }


    public static int nextInt(int min, int max){
        Random rand= new Random();
        int tmp = Math.abs(rand.nextInt());
        return tmp % (max - min + 1) + min;
    }

    
    public Integer updateCsPartsQRcode(Map<String, Object> map) throws Exception {
        return partsClient.updateCsPartsQRcode(map);
    }

    public Page<Map<String, Object>> queryCsPartsQRcodePageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) throws Exception {
        Integer total = partsClient.getCsPartsQRcodeCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Map<String, Object>> csPartsList = partsClient.getCsPartsQRcodeListByMap(param);
        page.setRows(csPartsList);
        return page;
    }


    public List<Map<String, Object>> getHistoryByQRcode(String QRcode) throws Exception {
        return partsClient.getHistoryByQRcode(QRcode);
    }

    public Map<String, Object> getPartsByQRcode(String QRcode) throws Exception {
        return partsClient.getPartsByQRcode(QRcode);
    }

    public Page<Map<String, Object>> getPartsSellNumByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) throws Exception {
        Integer total = partsClient.getPartsSellNumCount(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<Map<String, Object>> csPartsList = partsClient.getPartsSellNum(param);
        for(Map<String, Object> a:csPartsList){
            String partsTypeId = a.get("partsType").toString();
            ProductType type = productTypeClient.getProductTypeById(partsTypeId);
            a.put("partsType", type.getTypeName());
        }
        page.setRows(csPartsList);
        return page;
    }


    public void downloadExcelPrint(HttpServletRequest request, HttpServletResponse response){
        String realPath = request.getParameter("realPath");
        String partsId = request.getParameter("partsId");
        try {
            String startCode = realPath.split(",")[0];
            String endCode = realPath.split(",")[1];
            List<CsPartsQrCode> list = partsClient.getPartsQrcodeListEntity(partsId, startCode, endCode);


            // 每次写100行数据，就刷新数据出缓存
            XSSFWorkbook wb = new XSSFWorkbook(); // keep 100 rows in memory,
            Sheet sh = wb.createSheet();
            // 这个是业务数据
            String[] titles = {"序号", "二维码编码", "生成时间", "配件编码", "配件名称", "配件品牌", "配件型号", "配件产地", "配件单价", "配件质保期", "损坏赔付金额"};
            Row row = sh.createRow(0);
            // 第一行设置标题
            for (int i = 0; i < titles.length; i++) {
                String title = titles[i];
                Cell cell1 = row.createCell(i);
                cell1.setCellValue(title);
            }

            // 导出数据
            for (int rowNum = 0; rowNum < list.size(); rowNum++) {

                Row rowData = sh.createRow(rowNum + 1);
                // TbClass 这个是我的业务类，这个是根据业务来进行填写数据
                // 第一列
                Cell cellDataA = rowData.createCell(0);
                cellDataA.setCellValue(list.get(rowNum).getCode());
                // 第二列
                Cell cellDataB = rowData.createCell(1);
                cellDataB.setCellValue(list.get(rowNum).getQRcode());
                // 第三列
                Cell cellDataC = rowData.createCell(2);
                cellDataC.setCellValue(list.get(rowNum).getCreateTime());
                // 第四列
                Cell cellDataD = rowData.createCell(3);
                cellDataD.setCellValue(list.get(rowNum).getParts_number());
                // 第五列
                Cell cellDataE = rowData.createCell(4);
                cellDataE.setCellValue(list.get(rowNum).getPartsName());
                // 第六列
                Cell cellDataF = rowData.createCell(5);
                cellDataF.setCellValue(list.get(rowNum).getParts_brand());
                // 第七列
                Cell cellDataG = rowData.createCell(6);
                cellDataG.setCellValue(list.get(rowNum).getParts_model());
                // 第八列
                Cell cellDataH = rowData.createCell(7);
                cellDataH.setCellValue(list.get(rowNum).getParts_place());
                // 第九列
                Cell cellDataI = rowData.createCell(8);
                cellDataI.setCellValue(list.get(rowNum).getParts_price());
                // 第十列
                Cell cellDataJ = rowData.createCell(9);
                cellDataJ.setCellValue(list.get(rowNum).getGuaranteePeriod());
                // 第十一列 TODO
                Cell cellDataK = rowData.createCell(10);
                cellDataK.setCellValue("");
            }


            String fileName = "二维码数据.xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            wb.write(response.getOutputStream());
            wb.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
